package com.zhugang.week13.stack;

/**
 * @program algorithms
 * @description: TripleInOne
 * @author: chanzhugang
 * @create: 2022/11/03 19:32
 */
public class TripleInOne {

    /**
     * 面试题03.01 三合一
     * https://leetcode.cn/problems/three-in-one-lcci/
     * <p>
     * 一个数组实现三个栈, 主要是下标的操作，画个图理解
     *
     * @param stackSize
     */

    private int[] array;
    private int n;
    /**
     * 保存每个栈的栈顶元素
     */
    private int[] top = new int[3];

    public TripleInOne(int stackSize) {
        array = new int[stackSize * 3];
        n = stackSize * 3;
        top[0] = -3;
        top[1] = -2;
        top[2] = -1;

    }

    public void push(int stackNum, int value) {
        // 三个栈依次存，每存一个元素跳3个下标
        if (top[stackNum] + 3 >= n) {
            // 数组满了
            return;
        }
        // 下标加3
        top[stackNum] += 3;
        array[top[stackNum]] = value;
    }

    public int pop(int stackNum) {
        if (top[stackNum] < 0) {
            // 没有元素
            return -1;
        }
        int ret = array[top[stackNum]];
        // 下标减3
        top[stackNum] -= 3;
        return ret;
    }

    public int peek(int stackNum) {
        if (top[stackNum] < 0) {
            return -1;
        }
        return array[top[stackNum]];
    }

    public boolean isEmpty(int stackNum) {
        return top[stackNum] < 0;
    }
}